import javalang

# Java 代码示例
java_code = """
public class Calculator {
    private int value;
    
    public Calculator(int initialValue) {
        this.value = initialValue;
    }
    
    public int add(int number) {
        value += number;
        return value;
    }
    
    public static void main(String[] args) {
        Calculator calc = new Calculator(0);
        int result = calc.add(5);
        System.out.println("Result: " + result);
    }
}
"""

# 解析 Java 代码
tree = javalang.parse.parse(java_code)


def analyze_java_code(tree):
    """分析 Java 代码结构"""
    classes = []
    methods = []
    fields = []

    for path, node in tree:
        if isinstance(node, javalang.tree.ClassDeclaration):
            classes.append({"name": node.name, "modifiers": node.modifiers})
        elif isinstance(node, javalang.tree.MethodDeclaration):
            methods.append(
                {
                    "name": node.name,
                    "return_type": (
                        node.return_type.name if node.return_type else "void"
                    ),
                    "parameters": (
                        [param.name for param in node.parameters]
                        if node.parameters
                        else []
                    ),
                    "modifiers": node.modifiers,
                }
            )
        elif isinstance(node, javalang.tree.FieldDeclaration):
            for declarator in node.declarators:
                fields.append(
                    {
                        "name": declarator.name,
                        "type": node.type.name,
                        "modifiers": node.modifiers,
                    }
                )

    return {"classes": classes, "methods": methods, "fields": fields}


import json

analysis = analyze_java_code(tree)
print(json.dumps(analysis, ensure_ascii=False))
